<!--<script setup>-->
<!--import { nextTick, reactive, ref } from "vue";-->
<!--import request from "@/utils/request";-->
<!--import {ElMessage} from "element-plus";-->
<!--import config from "../../../config";-->
<!--import {useUserStore} from "@/stores/user";-->


<!--const name = ref('')-->
<!--const pageNum = ref(1)-->
<!--const pageSize = ref(5)-->
<!--const total = ref(0)-->

<!--const userStore = useUserStore()-->
<!--const token = userStore.getBearerToken-->
<!--const auths =  userStore.getAuths-->

<!--const state = reactive({-->
<!--  tableData: [],-->
<!--  form: {}-->
<!--})-->

<!--const valueHtml = ref('')  // 富文本内容-->

<!--state.goodsOptions = []-->
<!--request.get('/goods').then(res => state.goodsOptions = res.data)-->
<!--state.userOptions = []-->
<!--request.get('/user').then(res => state.userOptions = res.data)-->


<!--const multipleSelection = ref([])-->

<!--// 批量删除-->
<!--const handleSelectionChange = (val) => {-->
<!--  multipleSelection.value = val-->
<!--}-->

<!--const confirmDelBatch = () => {-->
<!--  if (!multipleSelection.value || !multipleSelection.value.length) {-->
<!--    ElMessage.warning("请选择数据")-->
<!--    return-->
<!--  }-->
<!--  const idArr = multipleSelection.value.map(v => v.id)-->
<!--  request.post('/cart/del/batch', idArr).then(res => {-->
<!--    if (res.code === '200') {-->
<!--      ElMessage.success('操作成功')-->
<!--      load()  // 刷新表格数据-->
<!--    } else {-->
<!--      ElMessage.error(res.msg)-->
<!--    }-->
<!--  })-->
<!--}-->

<!--const load = () => {-->
<!--  request.get('/cart/page', {-->
<!--    params: {-->
<!--      name: name.value,-->
<!--      pageNum: pageNum.value,-->
<!--      pageSize: pageSize.value-->
<!--    }-->
<!--  }).then(res => {-->
<!--    state.tableData = res.data.records-->
<!--    total.value = res.data.total-->
<!--  })-->
<!--}-->
<!--load()  // 调用 load方法拿到后台数据-->

<!--const reset = () => {-->
<!--  name.value = ''-->
<!--  load()-->
<!--}-->

<!--const dialogFormVisible = ref(false)-->

<!--const rules = reactive({-->
<!--  name: [-->
<!--    { required: true, message: '请输入名称', trigger: 'blur' },-->
<!--  ]-->
<!--})-->
<!--const ruleFormRef = ref()-->

<!--// 新增-->
<!--const handleAdd = () => {-->
<!--  dialogFormVisible.value = true-->
<!--  nextTick(() => {-->
<!--    ruleFormRef.value.resetFields()-->
<!--    state.form = {}-->
<!--    valueHtml.value = ''  // 富文本-->
<!--  })-->
<!--}-->

<!--// 保存-->
<!--const save = () => {-->
<!--  ruleFormRef.value.validate(valid => {   // valid就是校验的结果-->
<!--    if (valid) {-->
<!--      state.form.content = valueHtml.value  // 富文本保存内容-->
<!--      request.request({-->
<!--        url: '/cart',-->
<!--        method: state.form.id ? 'put' : 'post',-->
<!--        data: state.form-->
<!--      }).then(res => {-->
<!--        if (res.code === '200') {-->
<!--          ElMessage.success('保存成功')-->
<!--          dialogFormVisible.value = false-->
<!--          load()  // 刷新表格数据-->
<!--        } else {-->
<!--          ElMessage.error(res.msg)-->
<!--        }-->
<!--      })-->
<!--    }-->
<!--  })-->
<!--}-->

<!--// 编辑-->
<!--const handleEdit = (raw) => {-->
<!--  dialogFormVisible.value = true-->
<!--  nextTick(() => {-->
<!--    ruleFormRef.value.resetFields()-->
<!--    state.form = JSON.parse(JSON.stringify(raw))-->
<!--    valueHtml.value = raw.content  // 富文本-->
<!--  })-->
<!--}-->

<!--// 删除-->
<!--const del = (id) => {-->
<!--  request.delete('/cart/' + id).then(res => {-->
<!--    if (res.code === '200') {-->
<!--      ElMessage.success('操作成功')-->
<!--      load()  // 刷新表格数据-->
<!--    } else {-->
<!--      ElMessage.error(res.msg)-->
<!--    }-->
<!--  })-->
<!--}-->

<!--// 导出接口-->
<!--const exportData = () => {-->
<!--  window.open(`http://${config.serverUrl}/cart/export`)-->
<!--}-->


<!--const handleImportSuccess = () => {-->
<!--  // 刷新表格-->
<!--  load()-->
<!--  ElMessage.success("导入成功")-->
<!--}-->

<!--const handleFileUploadSuccess = (res) => {-->
<!--  state.form.file = res.data-->
<!--  ElMessage.success('上传成功')-->
<!--}-->
<!--const handleImgUploadSuccess = (res) => {-->
<!--  state.form.img = res.data-->
<!--  ElMessage.success('上传成功')-->
<!--}-->
<!--</script>-->

<!--<template>-->
<!--  <div>-->
<!--    <div>-->
<!--      <el-input v-model="name" placeholder="请输入名称" class="w300" />-->
<!--      <el-button type="primary" class="ml5" @click="load">-->
<!--        <el-icon style="vertical-align: middle">-->
<!--          <Search />-->
<!--        </el-icon>  <span style="vertical-align: middle"> 搜索 </span>-->
<!--      </el-button>-->
<!--      <el-button type="warning" class="ml5" @click="reset">-->
<!--        <el-icon style="vertical-align: middle">-->
<!--          <RefreshLeft />-->
<!--        </el-icon>  <span style="vertical-align: middle"> 重置 </span>-->
<!--      </el-button>-->

<!--    </div>-->

<!--    <div style="margin: 10px 0">-->
<!--      <el-popconfirm title="您确定删除吗？" @confirm="confirmDelBatch" v-if="auths.includes('cart.deleteBatch')">-->
<!--        <template #reference>-->
<!--          <el-button type="danger">-->
<!--            <el-icon style="vertical-align: middle">-->
<!--              <Remove />-->
<!--            </el-icon>  <span style="vertical-align: middle"> 批量删除 </span>-->
<!--          </el-button>-->
<!--        </template>-->
<!--      </el-popconfirm>-->
<!--    </div>-->

<!--    <div style="margin: 10px 0">-->
<!--      <el-table :data="state.tableData" stripe border  @selection-change="handleSelectionChange">-->
<!--        <el-table-column type="selection" width="55" />-->
<!--      <el-table-column prop="id" label="编号"></el-table-column>-->
<!--      <el-table-column label="商品"><template #default="scope"><span v-if="scope.row.goodsId">{{ state.goodsOptions.find(v => v.id === scope.row.goodsId) ? state.goodsOptions.find(v => v.id === scope.row.goodsId).name : '' }}</span></template></el-table-column>-->
<!--      <el-table-column prop="num" label="商品数量"></el-table-column>-->
<!--      <el-table-column label="用户"><template #default="scope"><span v-if="scope.row.userId">{{ state.userOptions.find(v => v.id === scope.row.userId) ? state.userOptions.find(v => v.id === scope.row.userId).name : '' }}</span></template></el-table-column>-->

<!--        <el-table-column label="操作" width="100">-->
<!--          <template #default="scope">-->
<!--            <el-popconfirm title="您确定删除吗？" @confirm="del(scope.row.id)" v-if="auths.includes('cart.delete')">-->
<!--              <template #reference>-->
<!--                <el-button type="danger">删除</el-button>-->
<!--              </template>-->
<!--            </el-popconfirm>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--      </el-table>-->
<!--    </div>-->

<!--    <div style="margin: 10px 0">-->
<!--      <el-pagination-->
<!--          @current-change="load"-->
<!--          v-model:current-page="pageNum"-->
<!--          v-model:page-size="pageSize"-->
<!--          background-->
<!--          layout="prev, pager, next"-->
<!--          :total="total"-->
<!--      />-->
<!--    </div>-->

<!--    <el-dialog v-model="dialogFormVisible" title="购物车信息" width="40%">-->
<!--      <el-form ref="ruleFormRef" :rules="rules" :model="state.form" label-width="80px" style="padding: 0 20px" status-icon>-->
<!--        <el-form-item prop="goodsId" label="商品">-->
<!--          <el-select clearable v-model="state.form.goodsId" placeholder="请选择"  style="width: 100%">-->
<!--            <el-option v-for="item in state.goodsOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--        <el-form-item prop="num" label="商品数量">-->
<!--          <el-input v-model="state.form.num" autocomplete="off"></el-input>-->
<!--        </el-form-item>-->
<!--        <el-form-item prop="userId" label="用户">-->
<!--          <el-select clearable v-model="state.form.userId" placeholder="请选择"  style="width: 100%">-->
<!--            <el-option v-for="item in state.userOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->

<!--      </el-form>-->
<!--      <template #footer>-->
<!--      <span class="dialog-footer">-->
<!--        <el-button @click="dialogFormVisible = false">取消</el-button>-->
<!--        <el-button type="primary" @click="save">-->
<!--          保存-->
<!--        </el-button>-->
<!--      </span>-->
<!--      </template>-->
<!--    </el-dialog>-->


<!--  </div>-->
<!--</template>-->



<script setup>
import { nextTick, reactive, ref } from "vue";
import request from "@/utils/request";
import {ElMessage} from "element-plus";
import config from "../../../config";
import {useUserStore} from "@/stores/user";


const name = ref('')
const pageNum = ref(1)
const pageSize = ref(5)
const total = ref(0)

const userStore = useUserStore()
const token = userStore.getBearerToken
const auths =  userStore.getAuths

const state = reactive({
  tableData: [],
  form: {}
})

const valueHtml = ref('')  // 富文本内容

state.goodsOptions = []
request.get('/goods').then(res => state.goodsOptions = res.data)
state.userOptions = []
request.get('/user').then(res => state.userOptions = res.data)


const multipleSelection = ref([])

// 批量删除
const handleSelectionChange = (val) => {
  multipleSelection.value = val

  request.post("/cart/cal", val).then(res => {
    if (res.data) {
      total.value = res.data
    }
  })
}

const confirmDelBatch = () => {
  if (!multipleSelection.value || !multipleSelection.value.length) {
    ElMessage.warning("请选择数据")
    return
  }
  const idArr = multipleSelection.value.map(v => v.id)
  request.post('/cart/del/batch', idArr).then(res => {
    if (res.code === '200') {
      ElMessage.success('操作成功')
      load()  // 刷新表格数据
    } else {
      ElMessage.error(res.msg)
    }
  })
}

const load = () => {
  request.get('/cart/front').then(res => {
    state.tableData = res.data
  })
}
load()  // 调用 load方法拿到后台数据

const reset = () => {
  name.value = ''
  load()
}

const dialogFormVisible = ref(false)

const rules = reactive({
  name: [
    { required: true, message: '请输入名称', trigger: 'blur' },
  ]
})
const ruleFormRef = ref()

// 新增
const handleAdd = () => {
  dialogFormVisible.value = true
  nextTick(() => {
    ruleFormRef.value.resetFields()
    state.form = {}
    valueHtml.value = ''  // 富文本
  })
}

// 保存
const save = () => {
  ruleFormRef.value.validate(valid => {   // valid就是校验的结果
    if (valid) {
      state.form.content = valueHtml.value  // 富文本保存内容
      request.request({
        url: '/cart',
        method: state.form.id ? 'put' : 'post',
        data: state.form
      }).then(res => {
        if (res.code === '200') {
          ElMessage.success('保存成功')
          dialogFormVisible.value = false
          load()  // 刷新表格数据
        } else {
          ElMessage.error(res.msg)
        }
      })
    }
  })
}

// 编辑
const handleEdit = (raw) => {
  dialogFormVisible.value = true
  nextTick(() => {
    ruleFormRef.value.resetFields()
    state.form = JSON.parse(JSON.stringify(raw))
    valueHtml.value = raw.content  // 富文本
  })
}

// 删除
const del = (id) => {
  request.delete('/cart/' + id).then(res => {
    if (res.code === '200') {
      ElMessage.success('操作成功')
      load()  // 刷新表格数据
    } else {
      ElMessage.error(res.msg)
    }
  })
}

// 导出接口
const exportData = () => {
  window.open(`http://${config.serverUrl}/cart/export`)
}


const handleImportSuccess = () => {
  // 刷新表格
  load()
  ElMessage.success("导入成功")
}

const handleFileUploadSuccess = (res) => {
  state.form.file = res.data
  ElMessage.success('上传成功')
}
const handleImgUploadSuccess = (res) => {
  state.form.img = res.data
  ElMessage.success('上传成功')
}

const changeNum = (row) => {
  request.put('/cart', row)
}
</script>

<template>
  <div>

    <div style="margin: 10px 0">
      <el-popconfirm title="您确定删除吗？" @confirm="confirmDelBatch">
        <template #reference>
          <el-button type="danger">
            <el-icon style="vertical-align: middle">
              <Remove />
            </el-icon>  <span style="vertical-align: middle"> 批量删除 </span>
          </el-button>
        </template>
      </el-popconfirm>
    </div>

    <div style="margin: 10px 0">
      <el-table :data="state.tableData" stripe border  @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="编号"></el-table-column>
        <el-table-column label="商品图片"><template #default="scope">
          <img v-if="scope.row.goods.imgs" style="width: 100px; height: 100px" :src="scope.row.goods.imgs[0].url" alt="">
        </template></el-table-column>
        <el-table-column label="商品"><template #default="scope"><span v-if="scope.row.goodsId">{{ scope.row.goods.name }}</span></template></el-table-column>
        <el-table-column label="商品价格"><template #default="scope"><span v-if="scope.row.goodsId" style="color: red; font-weight: bold">￥{{ scope.row.goods.price }}</span></template></el-table-column>
        <el-table-column prop="num" label="商品数量">
          <template #default="scope">
            <el-input-number v-model="scope.row.num" size="default" style="width: 120px" @change="changeNum(scope.row)"></el-input-number>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-popconfirm title="您确定删除吗？" @confirm="del(scope.row.id)">
              <template #reference>
                <el-button type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div style="box-shadow: 0 0 7px -2px rgba(0,0,0,.2); padding: 10px; border-radius: 10px; text-align: right">
      <div style="color: red">总价格：<span style="font-size: 24px">￥{{ total }}</span></div>

      <div style="margin-top: 10px"><el-button style="background-color: red; color: white" size="large">去结算</el-button></div>
    </div>

  </div>
</template>
